<?php

	/*
	## HOW TO USE CACHE CLASS
	 
	$cache = new Yomm_Caching("twitter-tweets", 3600, false);
	
	if($cache->isCached())
	{
		$return = $cache->getCache();
	} else {
		$return = $cache->putCache("INSERT YOUR CONTENT HERE WITH WHAT EVER YOU WANT TO!");
	}
	
	var_dump($cache->getStatus());
	
	var_dump($return);
	 
	*/

	/**
	 * 
	 * @author bsuter
	 *
	 */
	Class Yomm_Caching {
		
		private $identifier = null;
		
		private $cache_time = null;
		
		private $serialize = null;
		
		private $status = null;
		
		/**
		 * 
		 * @param $identifier [text] twitter-cache; facebook-events-cached; UNIQUE IDENTIFIER
		 * @param $cache_time [int] value to recache the file in seconds
		 * @param $serialize [boolean] serialize value while saving and unserliaze while loading content.
		 * @return void
		 */
		public function __construct($identifier, $cache_time = 3600, $serialize = false)
		{
			$this->identifier = $this->createFileHash($identifier);
			
			$this->cache_time = $cache_time;
			
			$this->serialize = $serialize;
		}
		
		/* private */
		
		private function createFileHash($identifier)
		{
			return md5(base64_encode($identifier) . md5(strlen($identifier)));
		}
		
		private function getCacheName($identifier)
		{
			return Yomm_Config::DIR_CACHE . $this->createFileHash($identifier);
		}
		
		private function setStatus($status)
		{
			$this->status = $status;
		}
		
		/* public */
		
		public function isCached()
		{
			if(file_exists($this->getCacheName($this->identifier))) // && )
			{
				
				$filemtime = filemtime($this->getCacheName($this->identifier));
				
				if((time() - $this->cache_time) < $filemtime)
				{
					$recache_seconds = round(($this->cache_time - (time() - $filemtime))/60);
					
					$this->setStatus("load content from cache file {$this->getCacheName($this->identifier)} time till recache: {$recache_seconds} min");
					return true;
				} else {
					$this->setStatus('the file exists but the cache value is expired!');
				}
				
			} else {
				$this->setStatus('the file does not exists in the cache!');
				return false;
			}
				
			return false;
		}
		
		public function getCache()
		{
			$return = Yomm_File::getContent($this->getCacheName($this->identifier));
			
			if($this->serialize)
				$return = unserialize($return);
				
			return $return;
		}
		
		public function putCache($value)
		{
			if($this->serialize)
				$value = serialize($value);
			
			Yomm_File::create($this->getCacheName($this->identifier), $value);
			
			return $value;
		}
		
		public function getStatus()
		{
			return $this->status;
		}
	}